import React, { useState, useEffect, useRef, useImperativeHandle } from 'react';
import { message, Row } from 'antd';
import ExecConditions from '../form/execConditions';
import Rules from '../form/rules';
import RuleSet from '../form/RuleSet';
import RulesScore from '../form/rulesScore';
import { IS_EXEC_CONDITION, STRATEGY_MODE } from 'src/utils/constant';
import { cloneDeep } from 'lodash';
import OtherBtn from '../form/otherBtn';
import { getRules, getRulesScore, validateActionsConfig, getRulesSet } from 'src/utils/json/index';
import DecisionMatrix from 'src/components/DecisionMatrix';
import DecideTable from 'src/components/DecideTable';
import ActionConfig from '../form/ActionConfig';
import useRiskTypes from '../../../../hook/useRiskTypes';

export default function StrategyConfig(props) {
  const {
    mode,
    variable,
    actions,
    config,
    appId,
    eventId,
    operator,
    reloadVariable,
    changedVariableStr,
    is_exec_condition,
    actionType,
    disabled,
    isHideTitle,
    using_variables,
    projectCode,
  } = props;

  const riskTypes = useRiskTypes();
  const riskLevels = props.codes.risk_level
    ? props.codes.risk_level.map((it) => {
        return { code: it.key, name: it.value };
      })
    : [];
  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集验证值
    getValue: (values, cb, showError = true) => {
      const { error, value } = getCommonFinallyConfig({ values, actionType, showError }); // 验证数据

      cb(value, error);
    },
  }));

  const strategyConfig = useRef({
    condition_groups: [],
    mode: {
      code: '',
      rule_set: {
        //决策集
        execute_mode: '',
        express_rules: [],
      },

      risk_weight: {
        //风险权重
        weight_calc_rules: [],
        weight_range_rules: [],
      }, //决策集
      score_card: {
        score_range_rules: [],
        score_calc_rules: [],
      }, //评分卡
      decision_table: {
        rows: [],
      }, //决策表
      decision_matrix: {
        rows: [],
        header_rows: [],
        header_cols: [],
      }, //决策矩阵
    },
  }); //普通策略配置对象

  const [value, setValue] = useState(strategyConfig.current);

  const _ruleset = useRef(null); //决策集
  const _weight = useRef(null); //风险权重
  const _score = useRef(null); //评分卡
  const _decisionTable = useRef(null); //决策表
  const _decisionMatrix = useRef(null); //决策矩阵

  const _conditionGroups = useRef(null); //前置条件

  useEffect(() => {
    if (!config) {
      return;
    }
    strategyConfig.current.mode = {
      ...strategyConfig.current.mode,
      ...config.mode,
    };
    strategyConfig.current.condition_groups = config.condition_groups;
    console.log(value, config);
    setValue(cloneDeep(strategyConfig.current)); // 这里只是为了让组件再次render，以后有时间再改
  }, [config]);

  // 初始化实例对象
  useEffect(() => {
    // 组件卸载时，重置strategyConfig,strategyFlowConfig
    return function clearMode() {
      strategyConfig.current = null;
    };
  }, []);

  /**  获取普通策略最终的配置信息
   * @param {String} actionType 如果为copy,则需要把rule_id去掉
   */
  function getCommonFinallyConfig({ values, actionType, showError }) {
    const finallyConfig = {};
    const configMode = {
      code: mode,
    };
    try {
      // 判断是否有执行条件
      // 如果有执行条件，则验证必填情况
      if (is_exec_condition === IS_EXEC_CONDITION._TRUE) {
        _conditionGroups.current.getValue((value, error) => {
          if (!error) {
            finallyConfig.pre_condition = value;
          } else {
            throw '执行条件配置有误';
          }
        });
      }
      // 判断是否有rules条件
      // 如果有，则验证必填情况
      if (mode) {
        switch (mode) {
          //决策集
          case STRATEGY_MODE._RULESET:
            // console.log(values);
            // 是个数组，不过现在只有一条，方便以后扩展
            strategyConfig.current.mode.rule_set = _ruleset.current.getValue(values);
            // console.log(strategyConfig.current.mode.express_rules);
            // return;
            // const newRule = Object.assign(
            //   [],
            //   getRules(strategyConfig.current.mode.express_rules, STRATEGY_MODE, mode, actionType)
            // );
            // console.log(newRule)
            // configMode.express_rules = [
            //   {
            //     conditions: newRule,
            //     condition_actions: validateActionsConfig(
            //       strategyConfig.current.mode.express_rules[0].condition_actions,
            //       mode
            //     ),
            //     condition_express: values.expression,
            //     name: strategyConfig.current.mode.express_rules[0].name || '',
            //     id: strategyConfig.current.mode.express_rules[0].id || randomKey(),
            //   },
            // ];
            configMode.rule_set = Object.assign(
              {},
              getRulesSet(strategyConfig.current.mode.rule_set, actionType, mode),
            );

            break;
          //风险权重
          case STRATEGY_MODE._WEIGHT:
            strategyConfig.current.mode.risk_weight.weight_calc_rules = _weight.current.getValue();
            configMode.risk_weight = {
              weight_calc_rules: Object.assign(
                [],
                getRules(strategyConfig.current.mode.risk_weight.weight_calc_rules, STRATEGY_MODE, mode, actionType),
              ),
              weight_range_rules: validateActionsConfig(
                strategyConfig.current.mode.risk_weight.weight_range_rules,
                mode,
              ),
            };

            break;
          //评分卡
          case STRATEGY_MODE._SCORE_CARD:
            const score_card = _score.current.getValue();
            // strategyConfig.current.mode.score_card.score_calc_rules = _score.current.getValue();
            configMode.score_card = {
              base_score_flag: score_card.base_score_flag,
              base_score: score_card.base_score,
              score_calc_rules: Object.assign([], getRulesScore(score_card.score_calc_rules, actionType)),
              score_range_rules: validateActionsConfig(strategyConfig.current.mode.score_card.score_range_rules, mode),
            };
            break;

          //决策表
          case STRATEGY_MODE._DECISION_TABLE:
            _decisionTable.current.getValue((value, error) => {
              if (!error) {
                configMode.decision_table = value;
              } else {
                throw error;
              }
            }, false);

            break;
          //决策矩阵
          case STRATEGY_MODE._DECISION_MATRIX:
            _decisionMatrix.current.getValue((value, error) => {
              if (!error) {
                configMode.decision_matrix = value;
              } else {
                throw error;
              }
            }, false);

            break;

          default:
            break;
        }
      }
      finallyConfig.mode = configMode;
      return {
        value: finallyConfig,
        error: null,
      };
    } catch (error) {
      if (showError) {
        message.warning(error);
      }
      return {
        error: error,
        value: {},
      };
    } finally {
      console.log('heh');
    }
  }
  return (
    <div>
      {is_exec_condition === IS_EXEC_CONDITION._TRUE && (
        <div className='tantuer-field-area tantuer-field-area-2'>
          {!isHideTitle && <div className='form-title'>执行条件</div>}
          <ExecConditions
            {...props}
            isOld={props.isOld}
            projectCode={projectCode}
            isCompare={props.isCompare}
            variable={variable}
            using_variables={using_variables}
            value={strategyConfig.current.pre_condition || []}
            disabled={disabled}
            hidden={is_exec_condition !== IS_EXEC_CONDITION._TRUE}
            operator={operator}
            compareData={
              (props.compareData && props.compareData.config && props.compareData.config.pre_condition) || []
            }
            strategyId={props.id}
            createRef={_conditionGroups}
          />
        </div>
      )}
      {mode && (
        <div className='tantuer-field-area'>
          {!isHideTitle && <div className='form-title'>组件配置</div>}
          {mode === STRATEGY_MODE._RULESET && (
            <RuleSet
              {...props}
              actions={actions}
              isShowRules={eventId}
              variable={variable}
              using_variables={using_variables}
              operator={operator}
              projectCode={projectCode}
              reloadVariable={() => reloadVariable()}
              createRefR={_ruleset}
              changedVariableStr={changedVariableStr}
              value={strategyConfig.current.mode.rule_set.express_rules}
              execute_mode={strategyConfig.current.mode.rule_set.execute_mode}
              onComplete={reloadVariable}
              codes={props.codes}
              compareData={
                (props.compareData &&
                  props.compareData.config &&
                  props.compareData.config.mode &&
                  props.compareData.config.mode.rule_set) ||
                {}
              }
              disabled={disabled}
              riskTypes={riskTypes}
              riskLevels={riskLevels}
            />
          )}

          {/* 决策集 */}
          {/* {mode === STRATEGY_MODE._RULESET && (
            <Rules
              {...props}
              isShowRules={eventId}
              variable={variable}
              using_variables={using_variables}
              operator={operator}
              eventId={eventId}
              appId={appId}
              reloadVariable={() => reloadVariable()}
              createRef={_ruleset}
              changedVariableStr={changedVariableStr}
              value={strategyConfig.current.mode.express_rules[0].condition_rules}
              compareData={
                (props.compareData &&
                  props.compareData.config &&
                  props.compareData.config.mode &&
                  props.compareData.config.mode.express_rules &&
                  props.compareData.config.mode.express_rules[0] &&
                  props.compareData.config.mode.express_rules[0].condition_rules) ||
                []
              }
              disabled={disabled}
              riskTypes={riskTypes}
            />
          )} */}
          {/* 风险权重 */}
          {mode === STRATEGY_MODE._WEIGHT && (
            <Rules
              {...props}
              isShowRules={eventId}
              variable={variable}
              using_variables={using_variables}
              operator={operator}
              eventId={eventId}
              appId={appId}
              reloadVariable={() => reloadVariable()}
              createRef={_weight}
              changedVariableStr={changedVariableStr}
              value={strategyConfig.current.mode.risk_weight.weight_calc_rules}
              compareData={
                (props.compareData &&
                  props.compareData.config &&
                  props.compareData.config.mode &&
                  props.compareData.config.mode.risk_weight &&
                  props.compareData.config.mode.risk_weight.weight_calc_rules) ||
                []
              }
              disabled={disabled}
              riskTypes={riskTypes}
              riskLevels={riskLevels}
            />
          )}
          {/* 评分卡 */}
          {mode === STRATEGY_MODE._SCORE_CARD && (
            <RulesScore
              {...props}
              isShowRules={eventId}
              variable={variable}
              using_variables={using_variables}
              eventId={eventId}
              appId={appId}
              reloadVariable={() => reloadVariable()}
              changedVariableStr={changedVariableStr}
              value={strategyConfig.current.mode.score_card}
              createRef={_score}
              compareData={
                (props.compareData &&
                  props.compareData.config &&
                  props.compareData.config.mode &&
                  props.compareData.config.mode.score_card) ||
                []
              }
              disabled={disabled}
              riskTypes={riskTypes}
              riskLevels={riskLevels}
            />
          )}
          {/* 决策表 */}
          {mode === STRATEGY_MODE._DECISION_TABLE && (
            <>
              <>
                {!props.disabled && (
                  <Row type='flex' justify='start' gutter={10} style={{ marginBottom: '10px' }}>
                    <OtherBtn eventId={eventId} appId={appId} onComplete={reloadVariable} codes={props.codes} />
                  </Row>
                )}
              </>
              <DecideTable
                {...props}
                variable={variable}
                using_variables={using_variables}
                actions={actions}
                operator={operator}
                value={strategyConfig.current.mode.decision_table}
                createRef={_decisionTable}
                disabled={disabled}
                compareData={
                  (props.compareData &&
                    props.compareData.config &&
                    props.compareData.config.mode &&
                    props.compareData.config.mode.decision_table) ||
                  {}
                }
                riskTypes={riskTypes}
                riskLevels={riskLevels}
              />
            </>
          )}
          {/* 决策矩阵 */}
          {mode === STRATEGY_MODE._DECISION_MATRIX && (
            <>
              <>
                {!props.disabled && (
                  <Row type='flex' justify='start' gutter={10} style={{ marginBottom: '10px' }}>
                    <OtherBtn eventId={eventId} appId={appId} onComplete={reloadVariable} codes={props.codes} />
                  </Row>
                )}
              </>
              <DecisionMatrix
                {...props}
                variable={variable}
                using_variables={using_variables}
                actions={actions}
                operator={operator}
                value={strategyConfig.current.mode.decision_matrix}
                createRef={_decisionMatrix}
                compareData={
                  (props.compareData &&
                    props.compareData.config &&
                    props.compareData.config.mode &&
                    props.compareData.config.mode.decision_matrix) ||
                  {}
                }
                disabled={disabled}
                riskTypes={riskTypes}
                riskLevels={riskLevels}
              />
            </>
          )}
        </div>
      )}

      {/* 决策集、决策表和决策矩阵以外的组件才有单独的动作配置 */}
      {mode &&
        (mode !== STRATEGY_MODE._DECISION_TABLE &&
          mode !== STRATEGY_MODE._DECISION_MATRIX &&
          mode !== STRATEGY_MODE._RULESET) && (
          <div className='tantuer-field-area'>
            {!isHideTitle && <div className='form-title'>动作配置</div>}

            {/* 风险权重 */}
            {mode === STRATEGY_MODE._WEIGHT && (
              <ActionConfig
                {...props}
                disabled={disabled}
                variable={variable}
                using_variables={using_variables}
                actions={actions}
                value={strategyConfig.current.mode.risk_weight.weight_range_rules}
                compareData={
                  (props.compareData &&
                    props.compareData.config &&
                    props.compareData.config.mode &&
                    props.compareData.config.mode.risk_weight &&
                    props.compareData.config.mode.risk_weight.weight_range_rules) ||
                  {}
                }
                onChange={(value) => (strategyConfig.current.mode.risk_weight.weight_range_rules = value)}
                type={STRATEGY_MODE._WEIGHT}
                isInitOne={true}
                riskTypes={riskTypes}
                riskLevels={riskLevels}
              />
            )}

            {/* 评分卡 */}
            {mode === STRATEGY_MODE._SCORE_CARD && (
              <ActionConfig
                {...props}
                disabled={disabled}
                variable={variable}
                using_variables={using_variables}
                actions={actions}
                value={strategyConfig.current.mode.score_card.score_range_rules}
                onChange={(value) => (strategyConfig.current.mode.score_card.score_range_rules = value)}
                type={STRATEGY_MODE._SCORE_CARD}
                isInitOne={true}
                compareData={
                  (props.compareData &&
                    props.compareData.config &&
                    props.compareData.config.mode &&
                    props.compareData.config.mode.score_card &&
                    props.compareData.config.mode.score_card.score_range_rules) ||
                  {}
                }
                riskTypes={riskTypes}
                riskLevels={riskLevels}
              />
            )}
          </div>
        )}
    </div>
  );
}
